package com.zkld.frame.controller;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.zkld.frame.dto.ResponseDTO;
import com.zkld.frame.service.UserService;
import com.zkld.frame.util.JWTUtil;
import com.zkld.frame.util.ResponseFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class VerificationAndLoginController {

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public ResponseDTO login(@RequestParam("userId")Integer userId,
                             @RequestParam("password")String password){
        boolean flag = userService.login(userId,password);

        if (flag){
            return ResponseFactory.getResponse(JWTUtil.createToken(userId, password),"success");
        }

        return ResponseFactory.getResponse(null,"用户名或密码错误");
    }

    @GetMapping("/authentication")
    public ResponseDTO Authentication(@RequestParam("userId")Integer userId,
                                      @RequestParam("password")String password,
                                      HttpServletRequest request){
        try {
            JWTUtil.isTrue(request.getHeader("token"),userId,password);
            return ResponseFactory.getResponse(null,"success");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ResponseFactory.getResponse(null,"Token不合法");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            return ResponseFactory.getResponse(null,"登录信息已过期");
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return ResponseFactory.getResponse(null,"Token不合法");
        }
    }

}
